package main

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/storage"
	"fyne.io/fyne/v2/widget"
	"github.com/skip2/go-qrcode"
)

func main() {
	// 创建Fyne应用
	myApp := app.New()
	myWindow := myApp.NewWindow("简陋-二维码生成器")
	// 创建输入框和按钮
	entry := widget.NewEntry()
	entry.SetPlaceHolder("请输入需要转换为二维码的文本")

	label := widget.NewLabel("")
	label.TextStyle = fyne.TextStyle{Bold: true}
	label.Hide()

	// 生成二维码按钮
	generateBtn := widget.NewButton("生成", func() {
		text := entry.Text
		if text == "" {
			label.SetText("不能为空，请输入需要转换为二维码的文本！")
			label.Show()
			return
		}
		label.Hide()

		// 打开文件保存对话框
		saveDialog := dialog.NewFileSave(
			func(writer fyne.URIWriteCloser, _ error) {
				if writer == nil {
					return
				}
				defer func(writer fyne.URIWriteCloser) {
					err := writer.Close()
					if err != nil {
						fmt.Println(err)
					}
				}(writer)
				// 生成二维码
				qr, err := qrcode.New(text, qrcode.Highest)
				if err != nil {
					dialog.ShowError(err, myWindow)
					return
				}
				// 将二维码写入文件
				pngData, err := qr.PNG(512)
				if err != nil {
					dialog.ShowError(err, myWindow)
					return
				}
				_, err = writer.Write(pngData)
				if err != nil {
					dialog.ShowError(err, myWindow)
					return
				}
				label.SetText("二维码图片保存成功！qrcode.png")
				label.Show()
			}, myWindow)

		saveDialog.SetFileName("qrcode.png")
		saveDialog.SetFilter(storage.NewExtensionFileFilter([]string{".png"}))
		saveDialog.Show()
	})

	// 布局
	content := container.NewVBox(
		entry,
		generateBtn,
		label,
	)

	myWindow.SetContent(content)
	myWindow.Resize(fyne.NewSize(400, 200))
	myWindow.ShowAndRun()
}
